package com.hundsun.yr.universal.p2p.presenter.impl;

import android.content.Context;
import android.text.TextUtils;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.common.MD5Utils;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.LoginBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.base.RequestInteractor;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestInteractorImpl;
import com.hundsun.yr.universal.p2p.listener.BaseMultiLoadedListener;
import com.hundsun.yr.universal.p2p.presenter.base.Presenter;
import com.hundsun.yr.universal.p2p.utils.AndroidDes3Util;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.GsonTool;
import com.hundsun.yr.universal.p2p.view.PasswordVerifyView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;

/**
 * @version V1.0
 * @Title: PasswordVerifyPresenterImpl.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @date 2016-1-19 上午10:13:56
 * @email:xujk13382@hundsun.com
 * @replace author:
 * @replace date:
 */
public class PasswordVerifyPresenterImpl implements Presenter, BaseMultiLoadedListener<String> {

    private Context mContext = null;
    private PasswordVerifyView mView = null;
    /**
     * 请求接口
     **/
    private RequestInteractor mInteractor = null;
    private HSSharedPreferences mConfigSP = null;
    private HSSharedPreferences hsSharedPreferences = null;

    public PasswordVerifyPresenterImpl(Context context, PasswordVerifyView view) {
        mContext = context;
        mView = view;
        mConfigSP = new HSSharedPreferences(context, Config.SPPath.file_configInfo);
        hsSharedPreferences=new HSSharedPreferences(context, Config.SPPath.file_userLoginedInfo);
        this.mInteractor = new StringRequestInteractorImpl(this);
    }

    @Override
    public void initialized() {
    }

    public void validateCredentials(String username, String password) {
        if (TextUtils.isEmpty(username)) {
            mView.showValidateError("用户名为空");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            mView.showValidateError("请输入登录密码");
            return;
        }

        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();
        try {
            map.put("phone", username);
            map.put("passwd", MD5Utils.getMD5String(password));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject jsonParams = CommTool.getJSONParams(map, mConfigSP.getShareProf(TaskConstants.TASK_CONFIG), zwgt_data);
        login(TaskConstants.TASK_LOGIN, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_index_test) + TaskConstants.TASK_LOGIN, Constants.EVENT_DATA, jsonParams
                , BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_index_test) + TaskConstants.TASK_LOGIN, "", mConfigSP.getShareProf(TaskConstants.TASK_CONFIG), zwgt_data), false);
    }

    @Override
    public void onSuccess(String task_name, int event_tag, String data) {
        mView.closeProgress();
        try {
            AdSlideBeen adSlideBeen = (AdSlideBeen) GsonTool.getInstanceByJson(AdSlideBeen.class,data);
            switch (task_name){
                case TaskConstants.TASK_LOGIN:
                //登录的接口
                //数据请求成功之后对数据进行解密存储等操作
                switch (adSlideBeen.code){
                    case Constants.REQUESTCODE_000000:
                        //对data进行解密
                        try{
                            String decode = AndroidDes3Util.decode(adSlideBeen.data, mConfigSP.getShareProf(TaskConstants.TASK_CONFIG),
                                    (Date.parse(adSlideBeen.timestamp)+"").substring((Date.parse(adSlideBeen.timestamp)+"").length() - 8,(Date.parse(adSlideBeen.timestamp)+"").length()));
                            String[] split = decode.split("\\n");
                            if (split[1].isEmpty()){
                                new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_error)).show();
                                hsSharedPreferences.putBoolean(UserInfo.ISLOGIN, false);
                                return;
                            }
                            //解密成功，循环写入json数组中
                            LoginBeen loginBeen = (LoginBeen) GsonTool.getInstanceByJson(LoginBeen.class,split[1]);
                            //将获得的数据存起来
                            //存放token
                            if (UserInfo.TOKENID == null || UserInfo.TOKENID.isEmpty()){
                                new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_error)).show();
                                return;
                            }
                            hsSharedPreferences.putShareProf(UserInfo.TOKENID,loginBeen.token);

                            if (UserInfo.USER_NO == null || UserInfo.USER_NO.isEmpty()){
                                new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_error)).show();
                                return;
                            }

                            //存放用户id
                            hsSharedPreferences.putShareProf(UserInfo.USER_NO,loginBeen.user_no);

                            //存放用户手机号
                            hsSharedPreferences.putShareProf(UserInfo.MOBILE,loginBeen.phone);

                            //存放账号，应该就是手机号
                            hsSharedPreferences.putShareProf(UserInfo.ACCOUNT,loginBeen.phone);

                            //身份证
                            hsSharedPreferences.putShareProf(UserInfo.CERT_NO,loginBeen.cert_no);

                            hsSharedPreferences.putShareProf(UserInfo.REALNAME,loginBeen.true_name);
                            hsSharedPreferences.putShareProf(UserInfo.LENDER, loginBeen.is_lender);
                            /**
                             * 保存用户开户状态
                             */
                            if (loginBeen.depository_bank_no != null && !loginBeen.depository_bank_no.isEmpty()){
                                //已开户
                                hsSharedPreferences.putShareProf(UserInfo.IF_ACCOUNT,"YES");
                            }else {
                                //已开户
                                hsSharedPreferences.putShareProf(UserInfo.IF_ACCOUNT,"NO");
                                new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.open_account)).show();
                            }

                            /**
                             * 用户是否设置了交易密码
                             */
                            if (loginBeen.set_paypwd_flag != null && !loginBeen.set_paypwd_flag.isEmpty()) {
                                if (TextUtils.equals(loginBeen.set_paypwd_flag, "1")) {
                                    //已经设置交易密码
                                    hsSharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "YES");
                                } else {
                                    hsSharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "NO");
                                }
                            } else {
                                hsSharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "NO");
                            }

                            /**
                             * 保存用户等级
                             */
                            if (loginBeen.level != null && !loginBeen.level.isEmpty()){
                                hsSharedPreferences.putShareProf(UserInfo.USERLEVEL,loginBeen.level);
                            } else {
                                hsSharedPreferences.putShareProf(UserInfo.USERLEVEL,"0");
                            }

                            /**
                             * 保存用户银行卡手机号
                             */
                            if (loginBeen.depository_bank_mobile != null && !loginBeen.depository_bank_mobile.isEmpty()){
                                hsSharedPreferences.putShareProf(UserInfo.BANKMOBILE,loginBeen.depository_bank_mobile);
                            } else {
                                hsSharedPreferences.putShareProf(UserInfo.BANKMOBILE,"");
                            }

                            /**
                             * 判断是否老用户
                             */
                            if (loginBeen.ctime != null && !loginBeen.ctime.isEmpty()){
                                //将时间转换成时间戳
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
                                //      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");//12小时制
                                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));

                                long time = simpleDateFormat.parse(loginBeen.ctime).getTime();
                                if (MathUtils.compare(time + "","1498147200000") <= 0){
                                    //老用户
                                    hsSharedPreferences.putBoolean(UserInfo.OLDUSER,true);
                                }else{
                                    hsSharedPreferences.putBoolean(UserInfo.OLDUSER,false);
                                }
                            } else {
                                hsSharedPreferences.putBoolean(UserInfo.OLDUSER,false);
                            }

                            hsSharedPreferences.putBoolean(UserInfo.ISLOGIN, true);

                            mView.navigateToSetGestureLock();
                        }catch(Exception e){
                            e.printStackTrace();
//                            new HSToast(mContext).showToast(mContext.getString(R.string.login_error));
                        }
                        break;
                    case Constants.REQUESTCODE_200000:
                        //用户名或者密码错误
                        new HSToast(mContext).showToast(mContext.getString(R.string.loginFail));
                        break;
                    case Constants.REQUESTCODE_100020:
                        //Header值为空--不做任何提示
                        break;
                    case Constants.REQUESTCODE_100010:
                        break;
                    default:
                        new HSToast(mContext).showCustomToast(adSlideBeen.msg);
                        break;
                }
                break;
            }
        } catch (Exception e){

        }
    }

    @Override
    public void onException(String task_name, String msg) {
        mView.closeProgress();
        new HSToast(mContext).showToast(msg);
    }

    /**
     * 重新登录啊
     * @param task_name
     * @param url
     * @param event_tag
     * @param params
     * @param header
     * @param isSwipeRefresh
     */
    private void login(String task_name, String url, int event_tag, JSONObject params,HashMap<String, String> header, boolean isSwipeRefresh) {
        if (NetUtils.isNetworkConnected(mContext)) {
            mView.showProgress("");
            mInteractor.getRequestData(task_name, url, event_tag, params, header);
        } else {
            mView.closeProgress();
            new HSToast(mContext).showToast(R.string.common_no_network);
        }
    }

}
